package auth

import (
	"blog/app/model/admin"
	authCondition "blog/app/services/condition/auth"
	Core "blog/core"
	"blog/utils/encryption"
	"blog/utils/tools"
	"errors"
	"time"
)

type Login struct {
}

func (receiver *Login) Login(account string, password string) (*admin.Admin, error) {
	var info admin.Admin
	var count int64
	Core.DbConnect.Model(Auth.AdminModel).Scopes(authCondition.SelectAccount(account)).Count(&count).Find(&info)
	if count == 0 {
		return nil, errors.New("帐号不存在或者密码错误")
	}

	if !encryption.Crypt.User.Verify(password, info.Password) {
		return nil, errors.New("帐号不存在或者密码错误")
	}

	return &info, nil
}

// UpdateLoginLast , 更新最后登录参数
func (receiver *Login) UpdateLoginLast(id int, ip string) {
	//data := tools.Tools.Ip.Check(ip)
	Core.DbConnect.Model(Auth.AdminModel).Where("id = ?", id).Updates(map[string]interface{}{
		"LastIp":   ip,
		"LastTime": int(time.Now().Unix()),
		//"Isp":      data.Isp,
		//"Province": data.Province,
		//"City":     data.City,
	})
}

func (receiver *Login) CreateLoginLog(id int, ip string) {
	data := tools.Tools.Ip.Check(ip)
	Core.DbConnect.Create(&admin.LoginLog{
		Ip:       ip,
		Isp:      data.Isp,
		Province: data.Province,
		City:     data.City,
	})
}
